package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.User;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * 用户业务层接口实现类
 */
@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 给手机号发送验证码
     *
     * @param phone
     * @param httpSession
     * @return
     */
    @Override
    public Integer sendMsg(String phone, HttpSession httpSession) throws Exception {
        //1生成验证码 通过工具类生成 验证码一般为4或6位
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.debug("**手机号为{}，验证码为{}**",phone,code);
        //2发送验证码
        if(false) {//永远不执行
            SMSUtils.sendMessage(phone, code.toString());
        }
        //3为了登录校验验证码 发送验证码将验证码存入session(临时方案-实际工作一定不会这么干----->redis)
//        httpSession.setAttribute(phone,code);
        redisTemplate.opsForValue().set("LOGIN_"+phone,code.toString(),5, TimeUnit.MINUTES);
        log.debug("发送验证码成功了");
        return code;
    }

    /**
     * 登录校验
     *
     * @param phone
     * @param code
     */
    @Override
    public void login(String phone, String code,HttpSession httpSession) {
        //1先从redis获取验证码
//        String sessionCode = (String)httpSession.getAttribute(phone).toString();
        String redisCode = (String)redisTemplate.opsForValue().get("LOGIN_"+phone);
        log.debug("登录获取用户输入验证码{}，获取redis验证码{}",code,redisCode);


        //2根据用户输入的验证码 跟 session中验证码进行对比
        //2.1如果验证码为空直接抛出异常
        if(StringUtils.isEmpty(code) || StringUtils.isEmpty(redisCode)){
            throw new BusinessException("请重新获取验证码");
        }
        //3如果验证码不一致抛出业务异常：验证码错误请重新输入
        if(!code.equals(redisCode)){
            throw new BusinessException("请输入正确的验证码");
        }
        //4如果验证码一致 根据手机查询user表看用户是否存在
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone,phone);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        //5.不存在用户，自动注册用户
        if(user == null){
            user = new User();
            user.setPhone(phone);//用户输入的手机号
            user.setStatus(1);//默认正常
            userMapper.insert(user);
        }
        //6.session存入
        httpSession.setAttribute("user",user);
        log.debug("**用户{}登录成功了**",phone);

        redisTemplate.delete(phone);
    }
}
